package yf.mall;

import com.alibaba.druid.sql.visitor.functions.Char;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Code {

    public static void readCode(String boxPath,String codePath){
        List<File> boxFiles = sortFileList(boxPath);
        List<File> codeFiles = sortFileList(codePath);
        for (int i = 0; i < boxFiles.size(); i++) {
            toSql(boxFiles.get(i),codeFiles.get(i));
        }
    }

    public static Integer boxNumber = 26;

    public static void toSql(File boxFile,File codeFile){
        StringBuffer sb = new StringBuffer();
        List<String> boxCodes = readCode(boxFile);
        boxCodes.remove(0);
        List<String> codes = readCode(codeFile);
        codes.remove(0);
        //1比20读取
        for (int i = 0; i < boxCodes.size(); i++) {
            String boxCode = boxCodes.get(i);
            int start = i*boxNumber;
            int end = (i+1)*boxNumber;
            if(start>=codes.size()){
                break;
            }
            if(end>codes.size()){
                end = codes.size();
            }
            for (int j = start; j < end; j++) {
                String code = codes.get(j);
                //insert into security_code(version,owner,agent_Code,recorder,goods_name,code,boxCode) values
                sb.append("('1', '公司', '01', '管理员','暂未绑定','"+code.trim()+"','"+boxCode.trim()+"'),").append("\r\n");
            }
        }
        System.out.print(sb.toString());
    }

    public static List<String> readCode(File file){
        List<String> res = new ArrayList<>();
        try {
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String str;
            while ((str = bufferedReader.readLine())!=null){
                res.add(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    //读取文件且按数字编号排序
    public static List<File> sortFileList(String path){
        List<File> list =  Arrays.asList(new File(path).listFiles());
//        list.sort(Comparator.comparing(a -> Integer.valueOf(StringUtils.substringBefore(a.getName().substring(0,3).trim().replace("（","("),"(").substring(1).trim())));
        list.sort(Comparator.comparing(a->a.getName()));
        return list;
    }




    public static void main(String[] args) {
        readCode("/Users/hxf/Desktop/box","/Users/hxf/Desktop/code");
    }
}
